package kr.pe.xissy.soulmate.controller;

import java.util.Locale;

import javax.servlet.http.HttpSession;

import kr.pe.xissy.soulmate.security.role.UserGrantedAuthority;
import kr.pe.xissy.soulmate.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LogInController {

	@Autowired
	protected UserService userService;

	@Autowired
	UserGrantedAuthority userGrantedAuthority;

	@RequestMapping(value = "/logIn", method = RequestMethod.GET)
	public ModelAndView login(Locale locale, Model model, HttpSession session) {

		ModelAndView modelAndView = new ModelAndView();
		SecurityContext sc = SecurityContextHolder.getContext();
		if (sc.getAuthentication().getAuthorities().contains(userGrantedAuthority)) {
			modelAndView.addObject("error", "AlreadyLoggedIn");
		} else {
			modelAndView.addObject("error", "needToLogIn");
		}

		// *.json으로 부터 로그인 페이지로 온 것이면 로그인 페이지 대신 json 객체를 뿌림.
		SavedRequest savedRequest = (SavedRequest)session.getAttribute(WebAttributes.SAVED_REQUEST);
		if (savedRequest != null) {
			String requestUrl = savedRequest.getRedirectUrl();

			if (requestUrl.endsWith(".json")) {
				modelAndView.setViewName("redirect:logIn.json");
				return modelAndView;
			}
		}

		modelAndView.setViewName("logIn");
		return modelAndView;
	}

}
